﻿using OpenQA.Selenium;
using System;

namespace Fluent
{
    public static class AlertMocker
    {
        public static void AsPhantomJSAlert(Browser browser, bool confirmReturn = true)
        {
            if (browser.Type == EBrowserType.PhantomJS)
            {
                var js = @"oldAlertObj = window.alert; oldConfirmObj = window.confirm;
                    window.alert = function(message) { lastAlert = message; };
                    window.confirm = function(message) { lastAlert = message; return " + confirmReturn.ToString().ToLower() + "; }";
                browser.ExecuteJS(js);
            }
        }

        public static bool IsExists(Browser browser, double timeout)
        {
            if (browser.Type == EBrowserType.PhantomJS)
            {
                try
                {
                    var alertMessage = browser.ExecuteJS<string>("return lastAlert;");
                    return true;
                }
                catch (InvalidOperationException)
                {
                    return false;
                }
            }
            else
            {
                try
                {
                    browser.GetDriver().SwitchTo().Alert();
                    return true;
                }
                catch (NoAlertPresentException)
                {
                    return false;
                }
            }
        }

        public static string GetText(Browser browser)
        {
            if (browser.Type == EBrowserType.PhantomJS)
            {
                return browser.ExecuteJS<string>("return lastAlert;").ToString();
            }
            else
            {
                return browser.GetDriver().SwitchTo().Alert().Text;
            }
        }

        public static void Accept(Browser browser)
        {
            if (browser.Type == EBrowserType.PhantomJS)
            {
                EndPhantomJSAlert(browser);
            }
            else
            {
                browser.GetDriver().SwitchTo().Alert().Accept();
            }
        }

        public static void Dismiss(Browser browser)
        {
            if (browser.Type == EBrowserType.PhantomJS)
            {
                EndPhantomJSAlert(browser);
            }
            else
            {
                browser.GetDriver().SwitchTo().Alert().Dismiss();
            }
        }

        private static void EndPhantomJSAlert(Browser browser)
        {
            browser.ExecuteJS(
                @"window.alert = oldAlertObj; window.confirm = oldConfirmObj;
                    if(lastAlert) { lastAlert = undefined; }");
        }
    }
}